<?php


namespace app\admin\controller;


use think\Db;
use think\Request;
use think\Validate;

class Reward extends Common
{
    public function rewardlist(){

//        return  create_list('users_agent_proportion','money,agent_name,recommend_agent_name,is_freeze');
        $list = Db::name('users_agent_proportion')->field('id,round(money/100,2) as money,status,agent_name,recommend_agent_name,is_freeze')->select();
        return view('',['list'=>$list]);
    }
    private function get_Data(){
        $data = input('param.');
        $agent = getRedisDbList('users_agent','id,name',[['id','>',1]]);
        $res = Validate::make()
            ->rule([
                'agent_id|上级合伙人'=>"require|number",
                'recommend_agent_id|下级合伙人' =>'require|number',
                'money|补贴金'=>'require|float'
            ]);
        if (!$res->check($data)) {
            die(clientReturnJson('error',$res->getError()));
        }
        $array = [
            "agent_id"=>$data['agent_id'],
            "recommend_agent_id"=>$data['recommend_agent_id'],
            "money"=>$data['money']*100,
            "agent_name"=>$this->getName($data['agent_id'],$agent),
            "recommend_agent_name"=>$this->getName($data['recommend_agent_id'],$agent),
            "is_freeze"=>isset($data['is_freeze']) && $data['is_freeze']=='on'?1:0,
            "status"=>isset($data['status']) && $data['status']=='on'?1:0,
        ];
        if(!$array['agent_name'] || !$array['recommend_agent_name']){
            die(clientReturnJson('error','合伙人选择错误'));
        }
        return $array;
    }
    public function addreward(){
        $agent = getRedisDbList('users_agent','id,name',[['id','>',1]]);
        if(Request()->isPost()){
            return checkRes(Db::name('users_agent_proportion')->insert($this->get_Data()),'添加');
        }else{
            return view('',['type'=>'addreward','agent'=>$agent]);
        }
    }
    public function editreward(){
        $agent = getRedisDbList('users_agent','id,name',[['id','>',1]]);
        if(Request()->isPost()){
            $id = input('param.id',0);
            if(!$id){
                return package(1002,'id错误！');
            }
            $res = Db::name('users_agent_proportion')->where('id',$id)->update($this->get_Data());
            return checkRes($res,'修改');
        }else{
            $info = Db::name('users_agent_proportion')
                ->where('id',input('param.id'))
                ->field('round(money/100,2) as money,agent_id,recommend_agent_id,status,is_freeze,id')
                ->find();
            return view('addreward',['type'=>'editreward','agent'=>$agent,'info'=>$info]);
        }
    }
    private function getName($id,$list){
        foreach ($list as $v){
            if ($id ==$v['id']) return $v['name'];
        }
    }
}